import os

import cv2
import numpy as np
import pandas as pd
from PySide6.QtCore import Qt
from PySide6.QtGui import QPixmap
from PySide6.QtWidgets import QCheckBox
from matplotlib import pyplot as plt


class ImageManager:
    def __init__(self, parent):
        self.parent = parent
        self.image_paths = {
            "label_showGreyImg": "",
            "label_showCurves": ""
        }

    def setImage(self, label_name, image_path):
        self.image_paths[label_name] = image_path
        self.updateImage(label_name)

    def updateImage(self, label_name):
        image_path = self.image_paths.get(label_name, "")
        if not os.path.exists(image_path):
            return

        # 加载图片
        pixmap = QPixmap(image_path)

        # 获取 QLabel 的尺寸
        label = getattr(self.parent, label_name)
        label_width = label.width()
        label_height = label.height()

        # 缩放图片以适应 QLabel 尺寸，同时保持宽高比
        scaled_pixmap = pixmap.scaled(label_width, label_height, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)

        # 在 QLabel 中显示图片
        label.setPixmap(scaled_pixmap)

        # 确保 QLabel 不会被图片撑大
        label.setFixedSize(scaled_pixmap.size())

def drawGreyImg(parent,las):
    # 格式转换
    all_df = pd.DataFrame(las.data, columns=las.keys())

    #提取出所有gamma列8+1一圈
    df = pd.concat([all_df.iloc[:, 2:10], all_df.iloc[:, 2]], axis=1)

    # 将DataFrame转换为numpy数组
    data = df.values

    # 确保数据是二维的
    if data.ndim != 2:
        raise ValueError("数据必须是二维的")

    # 将数据归一化到0-255之间
    data_normalized = (data - data.min()) / (data.max() - data.min()) * 255

    # 转换为8位整数
    data_uint8 = data_normalized.astype(np.uint8)

    # 创建灰度图像
    gray_image = data_uint8
    resized_image = cv2.resize(gray_image, (500, 3000), interpolation=cv2.INTER_LINEAR)  ###此处设置图像尺寸，2比50

    # 保存图像
    cv2.imwrite('runtime/greyImg.png', resized_image)

    parent.image_manager.setImage("label_showGreyImg", "runtime/greyImg.png")

def DrawLinesAndGetImg(parent,las):
    # 获取所有被选中的复选框,得到将要绘制的参数
    selected_checkboxes = []
    # 遍历布局中的所有项目
    for i in range(parent.verticalLayout_11.count()):
        item = parent.verticalLayout_11.itemAt(i)
        widget = item.widget()
        # 检查该项目是否为 QCheckBox 并且已被选中
        if isinstance(widget, QCheckBox) and widget.isChecked():
            selected_checkboxes.append(widget)
    items = [cb.text() for cb in selected_checkboxes]

    l=len(items)
    if l<4:
        l=4

    # 启用自动缩放
    parent.label_showCurves.setScaledContents(True)
    # 创建一个新的图形
    fig, axs = plt.subplots(1, l, figsize=(20, 10), sharey=True)

    # 伽马数据的索引
    gamma_keys = ['AGRM', 'AGR0', 'AGR1', 'AGR2', 'AGR3', 'AGR4', 'AGR5', 'AGR6', 'AGR7']

    print("绘制曲线"+str(items))
    gamma_indices = [las.keys().index(key) for key in items if key in las.keys()]

    # 绘制每一道伽马数据
    for i, idx in enumerate(gamma_indices):
        ax = axs[i]
        ax.plot(las.data[:, idx], las.index, label=las.keys()[idx])
        ax.set_xlabel(las.keys()[idx])
        ax.xaxis.tick_top()
        # ax.invert_yaxis()
        ax.grid(True)

    # 设置公共的Y轴标签
    axs[0].set_ylabel('Depth (m)')

    # 调整子图间距
    plt.tight_layout()

    # 保存图像
    plt.savefig("./runtime/gammaLines.png")

    parent.image_manager.setImage("label_showCurves","./runtime/gammaLines.png")